# -*- coding: utf-8 -*-

from formencode.api import Invalid
from tw.api import JSLink, js_function
from tw.forms.fields import SingleSelectField
from tw.jquery import jquery_js

from hotweb import Hotweb, HotwebAPIError

__all__ = ["HotwebField"]

hotweb_field_js = JSLink(modname=__name__, filename="static/hotweb_field.js")

class HotwebField(SingleSelectField):
    engine_name = "mako"
    template = "tw.hotweb.templates.hotweb_field"
    javascript = [jquery_js, hotweb_field_js]
    include_dynamic_js_calls = True
    show_error = True
    api_key = None
    api_url = None
    params = ["api_key", "api_url"]

    def update_params(self, d):
        api = Hotweb(api_key=self.api_key, api_url=self.api_url)

        try:
            result = api.PageSearch()
        except HotwebAPIError, e:
            errors = e.errors
        else:
            errors = []
            options = [("", u"ページを選択してください")]
            for page in result["pages"]:
                page_id = page["PageId"]
                try:
                    detail = api.PageDetail(page_id, ContentType='iframe')
                except HotwebAPIError, e:
                    errors += e.errors
                else:
                    options.append((detail["IFrameTag"], detail["Title"]))
            d["options"] = options

        if errors:
            d["error"] = Invalid(HotwebAPIError.compound_error_messages(errors),
                                 None, None)

        super(HotwebField, self).update_params(d)

        self.add_call(js_function("hotweb_field_init")(self.id))
